<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/6/13
 * Time: 11:27
 */

namespace Weixin\Controller;


use Weixin\Exception\WeixinException;
use Weixin\Request\Cookie\SetCookieRequest;
use Weixin\Request\User_weixin\AddUserWeixinRequest;
use Weixin\Request\Weixin\AddWeixinRequest;
use Weixin\Request\Weixin\FindWeixinRequest;
use Weixin\Request\Weixin\IsWeixinExistRequest;
use Weixin\Request\Weixin\UpdateSubscribeRequest;
use Weixin\Request\Weixin\UpdateWeixinRequest;
use Weixin\Service\AddUserService;
use Weixin\Service\AddUserWeixinService;
use Weixin\Service\AddWeixinService;
use Weixin\Service\FindConfigService;
use Weixin\Service\FindWeixinService;
use Weixin\Service\GetCookieService;
use Weixin\Service\IsWeixinExistService;
use Weixin\Service\SetCooieService;
use Weixin\Service\UpdateSubscribeService;
use Weixin\Service\UpdateWeixinService;

class IndexController extends WeixinController
{
    public function test()
    {
        $openid = I('get.openid', null);
        //dump($openid);
        $request = new IsWeixinExistRequest();
        $request->setOpenid($openid);
        $service = new IsWeixinExistService();
        $response = $service->run($request);
        /*if ($response->getItIsNull() == true) {
            echo 1;
        } else {
            echo 2;
        }*/
    }

    public function test2()
    {
        $service = new FindConfigService();
        $response = $service->run();

        if ($response->getAppIdNull() == true) {
            throw new WeixinException(30007);
        } else {
            $appid = $response->getAppId();
        }
        if ($response->getAppSecretNull() == true) {
            throw new WeixinException(30008);
        } else {
            $appsecret = $response->getAppSecret();
        }
        if ($response->getTokenNull() == true) {
            throw new WeixinException(30009);
        } else {
            $token = $response->getToken();
        }
        if ($response->getEncodingaeskeyNull() == true) {
            throw new WeixinException(30010);
        } else {
            $encodingaeskey = $response->getEncodingaeskey();
        }
        dump($appid);
        dump($appsecret);
        dump($token);
        dump($encodingaeskey);

    }


    public function load_wechat($type = '')
    {
        //查询微信配置信息
        $service = new FindConfigService();
        $response = $service->run();

        if ($response->getAppIdNull() == true) {
            throw new WeixinException(30007);
        } else {
            $appid = $response->getAppId();
        }
        if ($response->getAppSecretNull() == true) {
            throw new WeixinException(30008);
        } else {
            $appsecret = $response->getAppSecret();
        }
        if ($response->getTokenNull() == true) {
            throw new WeixinException(30009);
        } else {
            $token = $response->getToken();
        }
        if ($response->getEncodingaeskeyNull() == true) {
            throw new WeixinException(30010);
        } else {
            $encodingaeskey = $response->getEncodingaeskey();
        }

        static $wechat = array();
        $index = md5(strtolower($type));
        if (!isset($wechat[$index])) {
            // 定义微信公众号配置参数（这里是可以从数据库读取的哦）
            $options = array(
                'token' => $token, // 填写你设定的key
                'appid' => $appid, // 填写高级调用功能的app id, 请在微信开发模式后台查询
                'appsecret' => $appsecret, // 填写高级调用功能的密钥
                'encodingaeskey' => $encodingaeskey, // 填写加密用的EncodingAESKey（可选，接口传输选择加密时必需）
                /*'token' => 'meiyile', // 填写你设定的key
                'appid' => 'wxef1f874b78dadc3a', // 填写高级调用功能的app id, 请在微信开发模式后台查询
                'appsecret' => '0737ebdd4f15c4b0ab07041015678bd1', // 填写高级调用功能的密钥
                'encodingaeskey' => 'JNy9JNUsBxHuh0WEGNokpN0wsqJmVTqYdOaMxFFJPCw', // 填写加密用的EncodingAESKey（可选，接口传输选择加密时必需）*/
                'mch_id' => '', // 微信支付，商户ID（可选）
                'partnerkey' => '', // 微信支付，密钥（可选）
                'ssl_cer' => '', // 微信支付，双向证书（可选，操作退款或打款时必需）
                'ssl_key' => '', // 微信支付，双向证书（可选，操作退款或打款时必需）
                'cachepath' => '', // 设置SDK缓存目录（可选，默认位置在Wechat/Cache下，请保证写权限）
            );
            \Wechat\Loader::config($options);
            $wechat[$index] = \Wechat\Loader::get($type);
        }
        return $wechat[$index];
    }

    public function reply()
    {
        include APP_PATH . 'Wechat/Loader.php';
        $receive = $this->load_wechat('Receive');
        if ($receive->valid() === FALSE) {
            // 接口验证错误，记录错误日志
            // log_message('ERROR', "微信被动接口验证失败，{$wechat->errMsg}[{$wechat->errCode}]");
            // 退出程序
            exit($receive->errMsg);
        }

        /* 获取粉丝的openid */
        $openid = $receive->getRev()->getRevFrom();
        /*$data['openid'] = $openid;
        $result = M('test')->add($data);*/

        /* 记录接口日志，具体方法根据实际需要去完善 */
        // _logs();

        //通过openid查询数据库用户id
        $request = new IsWeixinExistRequest();
        $request->setOpenid($openid);
        $service = new IsWeixinExistService();
        $response = $service->run($request);

        if ($response->getItIsNull() == true) {
            //写入微信表
            $subscribe = 0;
            $request = new AddWeixinRequest();
            $request->setOpenid($openid);
            $request->setSubscribe($subscribe);

            $service = new AddWeixinService();
            $response = $service->run($request);
            if ($response->getItIsNull() == true) {
                throw new WeixinException(30001);
            } else {
                $weixin_id = $response->getWeixinId();
            }
            //dump($weixin_id);

            //写入用户表
            $service = new AddUserService();
            $response = $service->run();
            if ($response->getItIsNull() == true) {
                throw new WeixinException(30002);
            } else {
                $user_id = $response->getUserId();
            }
            //dump($user_id);

            //写入关联表
            $request = new AddUserWeixinRequest();
            $request->setWeixinId($weixin_id);
            $request->setUserId($user_id);

            $service = new AddUserWeixinService();
            $response = $service->run($request);
            if ($response->getItIsNull() == true) {
                throw new WeixinException(30003);
            }
        }

        //通过openid查询数据库用户信息
        $request = new FindWeixinRequest();
        $request->setOpenid($openid);
        $service = new FindWeixinService();
        $response = $service->run($request);
        // $id = $response->getId();
        // $nickname = $response->getNickName();
        $subscribe = $response->getSubscribe();
        // $headimgurl = $response->getHeadImgUrl();
        $update_time = $response->getUpdateTime();

        if ($subscribe == 0) {
            $user = $this->load_wechat('User');
            $userInfo = $user->getUserInfo($openid);
            if ($userInfo['subscribe'] == 1) {
                //更新微信信息
                $request = new UpdateWeixinRequest();
                $nickname = $userInfo['nickname'];
                $subscribe = $userInfo['subscribe'];
                $headimgurl = $userInfo['headimgurl'];
                $update_time = time();
                $request->setOpenId($openid);
                $request->setNickName($nickname);
                $request->setSubscribe($subscribe);
                $request->setHeadImgUrl($headimgurl);
                $request->setUpdateTime($update_time);
                $service = new UpdateWeixinService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30004);
                }
            }
        } else {
            $time = time() - $update_time;
            $deadline = 7 * 24 * 3600;
            if ($time > $deadline) {
                $user = $this->load_wechat('User');
                $userInfo = $user->getUserInfo($openid);
                $request = new UpdateWeixinRequest();
                $nickname = $userInfo['nickname'];
                $subscribe = $userInfo['subscribe'];
                $headimgurl = $userInfo['headimgurl'];
                $update_time = time();
                $request->setOpenId($openid);
                $request->setNickName($nickname);
                $request->setSubscribe($subscribe);
                $request->setHeadImgUrl($headimgurl);
                $request->setUpdateTime($update_time);
                $service = new UpdateWeixinService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30004);
                }
            }
        }

        /* 分别执行对应类型的操作 */
        switch ($receive->getRev()->getRevType()) {
            // 事件类型处理
            case \Wechat\WechatReceive::MSGTYPE_EVENT:
                $event = $receive->getRevEvent();
                return $this->_event(strtolower($event['event']), $openid);

            // 文本类型处理
            /*case \Wechat\WechatReceive::MSGTYPE_TEXT:
                $keys = $receive->getRevContent();
                return $this->_keys($keys);*/

            // 图片类型处理
            /*case \Wechat\WechatReceive::MSGTYPE_IMAGE:
                return $this->_image();*/
        }
    }

    function _event($event, $openid)
    {
        switch ($event) {
            case 'subscribe':
                /*$test = D('test');
                $data['content'] = 123;
                $data['openid'] = $openid;
                $test->add($data);*/

                $subscribe = true;
                $request = new UpdateSubscribeRequest();
                $request->setOpenId($openid);
                $request->setSubscribe($subscribe);
                $service = new UpdateSubscribeService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30006);
                }
                return;

            case 'unsubscribe':
                /*$test = D('test');
                $data['content'] = 456;
                $data['openid'] = $openid;
                $test->add($data);*/

                $subscribe = false;
                $request = new UpdateSubscribeRequest();
                $request->setOpenId($openid);
                $request->setSubscribe($subscribe);
                $service = new UpdateSubscribeService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30006);
                }
                exit("success");
        }
    }

    /*function _keys($keys)
    {
        $wechat = $this->load_wechat('Receive');
        return $wechat->text($keys)->reply();
    }

    function _image()
    {
        $wechat = $this->load_wechat('Receive');
        return $wechat->text('您发送了一张图片过来')->reply();
    }*/


    public function oauth()
    {
        //获取cookie
        $service = new GetCookieService();
        $response = $service->run();

        if ($response->getItIsNull() == true) {
            include APP_PATH . 'Wechat/Loader.php';
            //获取oauth
            $oauth = $this->load_wechat('Oauth');

            //获取token
            $token = $oauth->getOauthAccessToken();

            //是否获取到openid
            if (!$token['openid']) {
                $url = $oauth->getOauthRedirect("http://" . I("server.HTTP_HOST") . __SELF__, 'meiyile', 'snsapi_base');
                header("location: $url");
                die();
            }

            $openid = $token['openid'];

            //通过openid查询数据库用户id
            $request = new IsWeixinExistRequest();
            $request->setOpenid($openid);
            $service = new IsWeixinExistService();
            $response = $service->run($request);

            if ($response->getItIsNull() == true) {
                //写入微信表
                $subscribe = 0;
                $request = new AddWeixinRequest();
                $request->setOpenid($openid);
                $request->setSubscribe($subscribe);

                $service = new AddWeixinService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30001);
                } else {
                    $weixin_id = $response->getWeixinId();
                }
                //dump($weixin_id);

                //写入用户表
                $service = new AddUserService();
                $response = $service->run();
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30002);
                } else {
                    $user_id = $response->getUserId();
                }
                //dump($user_id);

                //写入关联表
                $request = new AddUserWeixinRequest();
                $request->setWeixinId($weixin_id);
                $request->setUserId($user_id);

                $service = new AddUserWeixinService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30003);
                }
            }

            //通过openid查询数据库用户信息
            $request = new FindWeixinRequest();
            $request->setOpenid($openid);
            $service = new FindWeixinService();
            $response = $service->run($request);
            // $id = $response->getId();
            // $nickname = $response->getNickName();
            $subscribe = $response->getSubscribe();
            // $headimgurl = $response->getHeadImgUrl();
            $update_time = $response->getUpdateTime();

            if ($subscribe == 0) {
                $user = $this->load_wechat('User');
                $userInfo = $user->getUserInfo($openid);
                if ($userInfo['subscribe'] == 1) {
                    //更新微信信息
                    $request = new UpdateWeixinRequest();
                    $nickname = $userInfo['nickname'];
                    $subscribe = $userInfo['subscribe'];
                    $headimgurl = $userInfo['headimgurl'];
                    $update_time = time();
                    $request->setOpenId($openid);
                    $request->setNickName($nickname);
                    $request->setSubscribe($subscribe);
                    $request->setHeadImgUrl($headimgurl);
                    $request->setUpdateTime($update_time);
                    $service = new UpdateWeixinService();
                    $response = $service->run($request);
                    if ($response->getItIsNull() == true) {
                        throw new WeixinException(30004);
                    }
                }
            } else {
                $time = time() - $update_time;
                $deadline = 7 * 24 * 3600;
                if ($time > $deadline) {
                    $user = $this->load_wechat('User');
                    $userInfo = $user->getUserInfo($openid);
                    $request = new UpdateWeixinRequest();
                    $nickname = $userInfo['nickname'];
                    $subscribe = $userInfo['subscribe'];
                    $headimgurl = $userInfo['headimgurl'];
                    $update_time = time();
                    $request->setOpenId($openid);
                    $request->setNickName($nickname);
                    $request->setSubscribe($subscribe);
                    $request->setHeadImgUrl($headimgurl);
                    $request->setUpdateTime($update_time);
                    $service = new UpdateWeixinService();
                    $response = $service->run($request);
                    if ($response->getItIsNull() == true) {
                        throw new WeixinException(30004);
                    }
                }
            }

            //设置cookie
            $request = new SetCookieRequest();
            $request->setOpenId($openid);
            $service = new SetCooieService();
            $service->run($request);
        }
    }
}